<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useCategoryStore } from '@/stores/category'
import { CATEGORY_ICONS } from '@/types'
import { showToast, showConfirmDialog } from 'vant'

const router = useRouter()
const categoryStore = useCategoryStore()

const activeTab = ref('expense')
const showAddDialog = ref(false)
const showIconPicker = ref(false)
const showColorPicker = ref(false)

// 表单数据
const formData = ref({
  name: '',
  type: 'expense' as 'expense' | 'income',
  icon: 'default' as keyof typeof CATEGORY_ICONS,
  color: '#1989fa'
})

// 预设颜色列表
const presetColors = [
  '#1989fa', '#07c160', '#ff976a', '#ff6034', '#ee0a24',
  '#ed6a0c', '#ff9800', '#ffc107', '#4caf50', '#2196f3',
  '#3f51b5', '#9c27b0', '#e91e63', '#f44336', '#795548',
  '#607d8b', '#00bcd4', '#009688', '#8bc34a', '#cddc39'
]

// 图标列表
const iconList = computed(() => {
  return Object.keys(CATEGORY_ICONS) as Array<keyof typeof CATEGORY_ICONS>
})

onMounted(async () => {
  await categoryStore.fetchCategories()
})

// 打开添加分类对话框
const onAddCategory = () => {
  formData.value = {
    name: '',
    type: activeTab.value as 'expense' | 'income',
    icon: 'default',
    color: '#1989fa'
  }
  showAddDialog.value = true
}

// 选择图标
const onSelectIcon = (icon: keyof typeof CATEGORY_ICONS) => {
  formData.value.icon = icon
  showIconPicker.value = false
}

// 选择颜色
const onSelectColor = (color: string) => {
  formData.value.color = color
  showColorPicker.value = false
}

// 保存分类
const onSaveCategory = async () => {
  if (!formData.value.name.trim()) {
    showToast('请输入分类名称')
    return
  }

  try {
    await categoryStore.createCategory({
      name: formData.value.name.trim(),
      type: formData.value.type,
      icon: formData.value.icon,
      color: formData.value.color,
      isSystem: false
    })
    
    showToast('添加成功')
    showAddDialog.value = false
    
    // 刷新分类列表
    await categoryStore.fetchCategories()
  } catch (error) {
    console.error('添加失败:', error)
    showToast('添加失败')
  }
}

// 删除分类
const onDeleteCategory = async (category: any) => {
  if (category.isSystem) {
    showToast('默认分类不能删除')
    return
  }

  try {
    await showConfirmDialog({
      title: '确认删除',
      message: `确定要删除分类"${category.name}"吗？删除后该分类下的交易记录将变为未分类。`,
    })

    await categoryStore.deleteCategory(category.id!)
    showToast('删除成功')
    
    // 刷新分类列表
    await categoryStore.fetchCategories()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      showToast('删除失败')
    }
  }
}
</script>

<template>
  <div class="categories-view">
    <van-nav-bar title="分类管理" left-text="返回" @click-left="router.back()">
      <template #right>
        <van-icon name="plus" size="20" @click="onAddCategory" />
      </template>
    </van-nav-bar>

    <van-tabs v-model:active="activeTab" sticky>
      <van-tab title="支出分类" name="expense">
        <div class="category-list">
          <div 
            v-for="category in categoryStore.expenseCategories" 
            :key="category.id"
            class="category-item"
          >
            <div class="category-icon" :style="{ backgroundColor: category.color + '20' }">
              <span :style="{ color: category.color }">
                {{ CATEGORY_ICONS[category.icon as keyof typeof CATEGORY_ICONS] || CATEGORY_ICONS.default }}
              </span>
            </div>
            <div class="category-info">
              <div class="category-name">{{ category.name }}</div>
              <div class="category-system" v-if="category.isSystem">默认分类</div>
            </div>
            <van-icon 
              name="delete-o" 
              class="delete-icon"
              size="20"
              @click="onDeleteCategory(category)"
              v-if="!category.isSystem"
            />
          </div>
        </div>
      </van-tab>

      <van-tab title="收入分类" name="income">
        <div class="category-list">
          <div 
            v-for="category in categoryStore.incomeCategories" 
            :key="category.id"
            class="category-item"
          >
            <div class="category-icon" :style="{ backgroundColor: category.color + '20' }">
              <span :style="{ color: category.color }">
                {{ CATEGORY_ICONS[category.icon as keyof typeof CATEGORY_ICONS] || CATEGORY_ICONS.default }}
              </span>
            </div>
            <div class="category-info">
              <div class="category-name">{{ category.name }}</div>
              <div class="category-system" v-if="category.isSystem">默认分类</div>
            </div>
            <van-icon 
              name="delete-o" 
              class="delete-icon"
              size="20"
              @click="onDeleteCategory(category)"
              v-if="!category.isSystem"
            />
          </div>
        </div>
      </van-tab>
    </van-tabs>

    <!-- 添加分类对话框 -->
    <van-popup v-model:show="showAddDialog" position="bottom" round :style="{ height: '60%' }">
      <div class="add-dialog">
        <div class="dialog-header">
          <van-button text @click="showAddDialog = false">取消</van-button>
          <div class="dialog-title">添加{{ formData.type === 'expense' ? '支出' : '收入' }}分类</div>
          <van-button type="primary" text @click="onSaveCategory">保存</van-button>
        </div>

        <div class="dialog-content">
          <!-- 分类名称 -->
          <van-cell-group inset>
            <van-field
              v-model="formData.name"
              label="分类名称"
              placeholder="请输入分类名称"
              maxlength="10"
              show-word-limit
            />
          </van-cell-group>

          <!-- 分类类型 -->
          <van-cell-group inset>
            <van-cell title="分类类型">
              <template #value>
                <van-radio-group v-model="formData.type" direction="horizontal">
                  <van-radio name="expense">支出</van-radio>
                  <van-radio name="income">收入</van-radio>
                </van-radio-group>
              </template>
            </van-cell>
          </van-cell-group>

          <!-- 图标选择 -->
          <van-cell-group inset>
            <van-cell title="选择图标" is-link @click="showIconPicker = true">
              <template #value>
                <div class="selected-icon" :style="{ backgroundColor: formData.color + '20' }">
                  <span :style="{ color: formData.color }">
                    {{ CATEGORY_ICONS[formData.icon] }}
                  </span>
                </div>
              </template>
            </van-cell>
          </van-cell-group>

          <!-- 颜色选择 -->
          <van-cell-group inset>
            <van-cell title="选择颜色" is-link @click="showColorPicker = true">
              <template #value>
                <div class="selected-color" :style="{ backgroundColor: formData.color }"></div>
              </template>
            </van-cell>
          </van-cell-group>
        </div>
      </div>
    </van-popup>

    <!-- 图标选择器 -->
    <van-popup v-model:show="showIconPicker" position="bottom" round :style="{ height: '50%' }">
      <div class="icon-picker">
        <div class="picker-header">
          <div class="picker-title">选择图标</div>
          <van-icon name="cross" @click="showIconPicker = false" />
        </div>
        <div class="icon-grid">
          <div 
            v-for="icon in iconList" 
            :key="icon"
            class="icon-item"
            :class="{ active: formData.icon === icon }"
            @click="onSelectIcon(icon)"
          >
            <div class="icon-preview" :style="{ backgroundColor: formData.color + '20' }">
              <span :style="{ color: formData.color }">
                {{ CATEGORY_ICONS[icon] }}
              </span>
            </div>
            <div class="icon-name">{{ icon }}</div>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 颜色选择器 -->
    <van-popup v-model:show="showColorPicker" position="bottom" round :style="{ height: '40%' }">
      <div class="color-picker">
        <div class="picker-header">
          <div class="picker-title">选择颜色</div>
          <van-icon name="cross" @click="showColorPicker = false" />
        </div>
        <div class="color-grid">
          <div 
            v-for="color in presetColors" 
            :key="color"
            class="color-item"
            :class="{ active: formData.color === color }"
            :style="{ backgroundColor: color }"
            @click="onSelectColor(color)"
          >
            <van-icon v-if="formData.color === color" name="success" color="white" size="16" />
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style scoped>
.categories-view {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20px;
}

.category-list {
  padding: 16px;
}

.category-item {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.category-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-right: 12px;
  flex-shrink: 0;
}

.category-info {
  flex: 1;
  min-width: 0;
}

.category-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 4px;
  color: #333;
}

.category-system {
  font-size: 12px;
  color: #999;
}

.delete-icon {
  color: #ff4444;
  padding: 8px;
  cursor: pointer;
  flex-shrink: 0;
}

/* 添加分类对话框 */
.add-dialog {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
}

.dialog-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.dialog-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px 0;
}

.dialog-content :deep(.van-cell-group) {
  margin-bottom: 16px;
}

.selected-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.selected-color {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  border: 2px solid #f5f5f5;
}

/* 图标选择器 */
.icon-picker,
.color-picker {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
}

.picker-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.icon-grid {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: background-color 0.2s;
}

.icon-item:active {
  background-color: #f5f5f5;
}

.icon-item.active {
  background-color: #e8f4ff;
}

.icon-preview {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-bottom: 8px;
}

.icon-name {
  font-size: 11px;
  color: #666;
  text-align: center;
  word-break: break-word;
}

/* 颜色选择器 */
.color-grid {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 16px;
}

.color-item {
  width: 100%;
  aspect-ratio: 1;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: transform 0.2s;
  border: 3px solid transparent;
}

.color-item:active {
  transform: scale(0.95);
}

.color-item.active {
  border-color: #666;
}
</style>
